package com.qdaily.ui.data.DataBase;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class PraiseDAO {

    private DBHelper dbOpenHelper;
    private static PraiseDAO praiseDAO;

    private PraiseDAO() {
        this.dbOpenHelper = DBHelper.dbHelper();
    }

    public static PraiseDAO getInstance() {
        if (praiseDAO == null) {
            praiseDAO = new PraiseDAO();
        }
        return praiseDAO;
    }

    public void save(int server_id, int genre, String praise_type) {

        if (!isExist(server_id, praise_type)) {
            SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put("server_id", server_id + "");
            values.put("praise_type", praise_type);
            values.put("genre", genre + "");
            db.insert("praiseHistory2", null, values);
        } else {
            update(server_id, genre, praise_type);
        }
    }

    public boolean isPraise(int server_id, String praise_type) {
        if (praise_type == null)
            return false;
        SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery("select * from praiseHistory2 where server_id=? and praise_type=? limit 1", new String[]{server_id + "", praise_type});
        boolean result = false;
        if (cursor.moveToFirst()) {
            if (cursor.getInt(2) == 1) //1表示赞，2表示未赞
                result = true;
        }
        cursor.close();
        return result;
    }

    public boolean isExist(int server_id, String praise_type) {
        SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery("select * from praiseHistory2 where server_id=? and praise_type=? limit 1", new String[]{server_id + "", praise_type});
        boolean result = false;
        if (cursor.moveToFirst()) {
            result = true;
        }
        cursor.close();
        return result;
    }

    public void delete(int server_id, String praise_type) {
        SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
        db.execSQL("delete from praiseHistory2 where server_id=? and praise_type=?", new String[]{server_id + "", praise_type});
    }

    //存在点赞就更改点赞状态
    public void update(int server_id, int genre, String praise_type) {
        SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
        db.execSQL("update praiseHistory2 SET genre=? where server_id=? and praise_type=?", new String[]{genre + "", server_id + "", praise_type});
    }
}
